<template>
  <div>
    <div style="left: 10px;top: 5px;position: fixed">
      <router-link to="/" class="router-link-active"><span class="el-icon-s-home">首页</span></router-link>
    </div>
    <div class="login">
      <h2>社团管理系统</h2>
      <div>
        <span>账号：&nbsp;&nbsp;</span>
        <el-input style="width: 200px" placeholder="请输入用户名" v-model="name" clearable class="input_style"></el-input>
        <span v-if="error.name" class="err-msg">{{error.name}}</span>
      </div>
      <div>
        <span>密码：&nbsp;&nbsp;</span>
        <el-input style="width: 200px" placeholder="请输入密码" v-model="pwd" show-password class="input_style"></el-input>
        <span v-if="error.pwd" class="err-msg">{{error.pwd}}</span>
      </div>
      <div>
        <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>
        <el-button type="primary" @click="toLogin" class="login_style">登录</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {login} from '@/api'
export default {
  name: "Login",
  data() {
    return {
      name: '',
      pwd: '',
      error: {
        name: '',
        pwd: ''
      },
      user:{}
    }
  },
  methods: {
    toLogin() {
      let user = {
        name: this.name,
        pwd: this.pwd
      };
      login(user).then((result) => {
        console.log(result);
        this.user = result.data.data.user;
        let token = result.data.data.token;
        let refreshToken = result.data.data.refreshToken;
        sessionStorage.setItem("token", token);
        sessionStorage.setItem("refreshToken", refreshToken);
        if (this.user.id != null) {
          sessionStorage.setItem('name', this.user.name);
          sessionStorage.setItem('cid', this.user.c_id);
          sessionStorage.setItem('status', this.user.status);
          if (this.user.status === 1) {
            this.$router.push({
              path: '/mainAdmin',
            });
          } else {
            this.$router.push({
              path: '/mainCom',
            });
          }
        }
      })
    }
  },

  created() {
    // 如果有 token 直接跳到 对应的界面去。
    if (sessionStorage.getItem("token") != null) {
      let status = sessionStorage.getItem("status");
      if (status == 1) {
        this.$router.push({
          path: '/mainAdmin',
        });
      } else {
        this.$router.push({
          path: '/mainCom',
        });
      }
    }
  }
}
</script>

<style>
.login{
  height: 200px;
  width: 300px;
  margin: 250px 40%;
  /*background-color: #99a9bf;*/
}

.login h2 {
  text-align: center;
}
.input_style{
  width: 200px;
  margin-bottom: 10px;
}
.login_style{
  width: 200px;
}
.router-link-active {
  text-decoration: none;
  color: black;
}
</style>
